package com.shanghaionstar.smart.presenter;

import android.animation.ObjectAnimator;
import android.net.wifi.ScanResult;
import android.os.Bundle;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;

import com.midea.iot.sdk.cloud.openapi.MSmartSDK;
import com.midea.iot.sdk.cloud.openapi.MSmartThirdManager;
import com.midea.iot.sdk.cloud.openapi.common.MSmartDataCallback;
import com.midea.iot.sdk.cloud.openapi.common.MSmartDeviceConfigStep;
import com.midea.iot.sdk.cloud.openapi.common.MSmartErrorMessage;
import com.midea.iot.sdk.cloud.openapi.common.MSmartKeyDefine;
import com.midea.iot.sdk.cloud.openapi.common.MSmartStepDataCallback;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.framework.mvp.base.IMVPScheduler;
import com.onstar.cn.framework.mvp.base.IMVPView;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.shanghaionstar.smart.SmartDeviceListFrg;
import com.shanghaionstar.smart.SmartHomeActivity;
import com.shanghaionstar.smart.SmartSettingWifiFrg;
import com.shanghaionstar.smart.adapter.ConfigureArg;
import com.shanghaionstar.smart.iview.ISmartConnectingView;
import com.shanghaionstar.smart.service.SmartHomeService;
import com.shanghaionstar.smart.util.NetUtil;

import rx.functions.Action1;

/**
 * Created by 7828wc on 2016/6/22.
 */
public class SmartConnectingPresenter extends BasePresenter<Object> {
    private BaseActivity mContext;
    private ISmartConnectingView mSmartConnectingView;
    private SmartHomeService service;
    private ObjectAnimator objectAnimator;
    private ConfigureArg arg;


    public SmartConnectingPresenter(IMVPScheduler mvpScheduler) {
        super(mvpScheduler);
    }

    @Override
    public void setView(IMVPView<Object> view) {
        super.setView(view);
        mSmartConnectingView = (ISmartConnectingView) view;
        mContext = (BaseActivity) mSmartConnectingView.onActivity();
        service = new SmartHomeService(mContext);
    }

    /**
     * 旋转
     */
    private void startRotate(ImageView connectingIv) {
        objectAnimator = ObjectAnimator.ofFloat(connectingIv, "rotation",
                0, 360).setDuration(
                2000);
        objectAnimator.setRepeatCount(-1);
        objectAnimator.setRepeatMode(Animation.RESTART);
        objectAnimator.setInterpolator(new LinearInterpolator());
        objectAnimator.start();
    }

    public void getArguments(Bundle bun) {
        if (bun != null) {
            arg = (ConfigureArg) bun.getSerializable("arg");
        }
    }

    /**
     * 调用这个接口的前提是手机已经连上设备热点（可提示用户手动去设置页面连接设备热点），
     * 并拿到routerSSID、routerPwd、路由器加密方式capabilities、deviceSSID这些信息，
     * 6.0之前的手机配网流程不变，接口也不变
     * 调用这个接口的前提是手机已经连上家庭路由（可提示用户手动去设置页面连接家庭路由器热点）
     */

    boolean isSettingWifi = false;

    private String currStep;

    public void bindDevice(ImageView connectingIv) {
        startRotate(connectingIv);
        final MSmartThirdManager manager = MSmartSDK.getInstance().getThirdManager();
        int configureType = manager.getConfigureTypeByQRCode(arg.mQRcode);
        ScanResult result = NetUtil.getScanResultBySsid(arg.routerSsid, mContext);
        final String deviceSsid = NetUtil.getMediaSsid(arg.mQRcode,mContext);
//        MSmartSDK.getInstance().getThirdManager().startConfigureDevice(result, arg.routerPw, configureType, deviceSsid, new MSmartStepDataCallback() {
//            @Override
//            public void onStepChanged(int i, int i1, Bundle bundle) {
////                totalStep	MSmartKeyDefine.KEY_TOTAL_STEP	int	总配置步骤数量
//////                currentStep	MSmartKeyDefine.KEY_CURRENT_STEP	int	当前配置步骤
//////                stepName	MSmartKeyDefine.KEY_STEP_NAME
//                int totalStep = bundle.getInt(MSmartKeyDefine.KEY_TOTAL_STEP);
//                int currentStep = bundle.getInt(MSmartKeyDefine.KEY_CURRENT_STEP);
//                int progress = (int) (((float) currentStep / totalStep) * 100);
//                mSmartConnectingView.showProgress(progress + "");
//                currStep = bundle.getString(MSmartKeyDefine.KEY_STEP_NAME);
//            }
//
//            @Override
//            public void onComplete(Object o) {
////                deviceID	MSmartKeyDefine.KEY_DEVICE_ID	String	设备ID
////                deviceType	MSmartKeyDefine.KEY_DEVICE_TYPE	String	设备类型
////                deviceSubType	MSmartKeyDefine.KEY_DEVICE_SUB_TYPE	String	设备子类型
////                deviceSSID	MSmartKeyDefine.KEY_DEVICE_SSID	String	设备热点名称(SSID)
////                SN	MSmartKeyDefine.KEY_DEVICE_SN
//                if(o instanceof Bundle)
//                    activeDevice(manager, (Bundle) o);
//            }
//
//            @Override
//            public void onError(MSmartErrorMessage mSmartErrorMessage) {
//                Bundle bundle = mSmartErrorMessage.getExtras();
////                String mUserOperation = bundle.getString("user_operation");
//                if (bundle.getBoolean(MSmartKeyDefine.KEY_NEED_USER_OPERATION)) {
//                    isSettingWifi = true;
//                    if (currStep.equals(MSmartDeviceConfigStep.ENABLE_WIFI.name()) || currStep.equals(MSmartDeviceConfigStep.CONNECT_ROUTER.name())) {
//                        String deviceSsid = arg.routerSsid;
//                        String devicePassword = arg.routerPw;
//                        goToWifiSetting(deviceSsid, devicePassword);
//                    } else if (currStep.equals(MSmartDeviceConfigStep.CONNECT_DEVICE_AP.name())) {
//                        String devicePassword = "12345678";
//                        goToWifiSetting(deviceSsid, devicePassword);
//                    }
//
//                } else {
//                    objectAnimator.cancel();
//                    manager.stopConfigureDevice();
//                    if (mContext instanceof SmartHomeActivity) {
//                        ((SmartHomeActivity) mContext).hasFailed = true;
//                    }
//                    mSmartConnectingView.connectError();
//                }
//
//            }
//        });
        MSmartSDK.getInstance().getThirdManager().startConfigureDevice(result, arg.routerPw, configureType, deviceSsid, new MSmartStepDataCallback<Bundle>() {
            @Override
            public void onStepChanged(int i, int i1, Bundle bundle) {
                int totalStep = bundle.getInt(MSmartKeyDefine.KEY_TOTAL_STEP)+1;
                int currentStep = bundle.getInt(MSmartKeyDefine.KEY_CURRENT_STEP);
                int progress = (int) (((float) currentStep / totalStep) * 100);
                mSmartConnectingView.showProgress(progress + "");
                currStep = bundle.getString(MSmartKeyDefine.KEY_STEP_NAME);
            }

            @Override
            public void onComplete(Bundle bundle) {
                    activeDevice(manager, bundle);
            }

            @Override
            public void onError(MSmartErrorMessage mSmartErrorMessage) {
                Bundle bundle = mSmartErrorMessage.getExtras();
//                String mUserOperation = bundle.getString("user_operation");
                if (bundle.getBoolean(MSmartKeyDefine.KEY_NEED_USER_OPERATION)) {
                    isSettingWifi = true;
                    if (currStep.equals(MSmartDeviceConfigStep.ENABLE_WIFI.name()) || currStep.equals(MSmartDeviceConfigStep.CONNECT_ROUTER.name())) {
                        String deviceSsid = arg.routerSsid;
                        String devicePassword = arg.routerPw;
                        goToWifiSetting(deviceSsid, devicePassword);
                    } else if (currStep.equals(MSmartDeviceConfigStep.CONNECT_DEVICE_AP.name())) {
                        String devicePassword = "12345678";
                        goToWifiSetting(deviceSsid, devicePassword);
                    }

                } else {
                    objectAnimator.cancel();
                    manager.stopConfigureDevice();
                    if (mContext instanceof SmartHomeActivity) {
                        ((SmartHomeActivity) mContext).hasFailed = true;
                    }
                    mSmartConnectingView.connectError();
                }
            }
        });
    }

    public void resumeActiviteDevice() {
        if (isSettingWifi) {
            final MSmartThirdManager manager = MSmartSDK.getInstance().getThirdManager();
            manager.resumeConfigureDevice();
        }
    }


    public void goToWifiSetting(String deviceId, String currStep) {
        SmartSettingWifiFrg settingWifiFrg = new SmartSettingWifiFrg();
        Bundle bundle = new Bundle();
        bundle.putString(MSmartKeyDefine.KEY_STEP_NAME, currStep);
        bundle.putString(MSmartKeyDefine.KEY_DEVICE_ID, deviceId);
        settingWifiFrg.setArguments(bundle);
        mContext.changeFragment(mContext.getSupportFragmentManager(), settingWifiFrg, SmartSettingWifiFrg.class, true);
    }


//    private void showProgress(Map<String, Object> map) {
//        try {
//            Object currentStep = map.get("currentStep");
//            Object totalStep = map.get("totalStep");
//            int cur = (Integer) currentStep;
//            int total = (Integer) totalStep;
//            int progress = (int) (((float) cur / total) * 100);
//            mSmartConnectingView.showProgress(progress + "");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    private void activeDevice(final MSmartThirdManager manager, Bundle bundle) {
        String accessToken = ((SmartHomeActivity) mContext).mAccessToken;
        String devName = NetUtil.getMediaSsid(arg.mQRcode,mContext);
        String deviceEncryptSN = manager.getDevEncryptSNFromQRCode(arg.mQRcode);
        String devSN = bundle.getString(MSmartKeyDefine.KEY_DEVICE_SN);
        String devType = bundle.getString(MSmartKeyDefine.KEY_DEVICE_TYPE);
        String devSubType = bundle.getString(MSmartKeyDefine.KEY_DEVICE_SUB_TYPE);
        final String deviceID = bundle.getString(MSmartKeyDefine.KEY_DEVICE_ID);
        mSmartConnectingView.setLoading(true);
//        manager.activeDevice(accessToken, deviceEncryptSN, devSN, devType, devSubType, devName, new MSmartDataCallback() {
//            @Override
//            public void onComplete(Object o) {
//                objectAnimator.cancel();
//                if(o instanceof Bundle) {
//                    bindService(((Bundle)o).getString(MSmartKeyDefine.KEY_DEVICE_ID));
//                    manager.stopConfigureDevice();
//                }else{
//                    mSmartConnectingView.setLoading(false);
//                }
//            }
//
//            @Override
//            public void onError(MSmartErrorMessage mSmartErrorMessage) {
//                objectAnimator.cancel();
//                mSmartConnectingView.setLoading(false);
//                manager.stopConfigureDevice();
//                if (mContext instanceof SmartHomeActivity) {
//                    ((SmartHomeActivity) mContext).hasFailed = true;
//                }
//                mSmartConnectingView.connectError();
//            }
//        });
        manager.activeDevice(accessToken, deviceEncryptSN, devSN, devType, devSubType, devName, new MSmartDataCallback<Bundle>() {
            @Override
            public void onComplete(Bundle bundle) {
                objectAnimator.cancel();
                mSmartConnectingView.showProgress(100 + "");
                bindService(deviceID);
                manager.stopConfigureDevice();
            }

            @Override
            public void onError(MSmartErrorMessage mSmartErrorMessage) {
                objectAnimator.cancel();
                mSmartConnectingView.setLoading(false);
                manager.stopConfigureDevice();
                if (mContext instanceof SmartHomeActivity) {
                    ((SmartHomeActivity) mContext).hasFailed = true;
                }
                mSmartConnectingView.connectError();
            }
        });

    }


    private void goToDeviceList() {
        SmartDeviceListFrg listFrg = new SmartDeviceListFrg();
        mContext.changeFragment(mContext.getSupportFragmentManager(), listFrg, SmartDeviceListFrg.class, true);
    }




    private void bindService(String deviceID) {
        mSmartConnectingView.setLoading(true);
        subscription = service.bindDevice(deviceID).subscribeOn(mvpScheduler.backgroundThread()).observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String json) {
                        mSmartConnectingView.setLoading(false);
                        goToDeviceList();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        mSmartConnectingView.setLoading(false);
                        if (mSmartConnectingView != null)
                            mSmartConnectingView.onResponseError((OnStarException) throwable);
                    }
                });
    }

    /**
     * 取消操作
     */
    public void cancel() {
        objectAnimator.cancel();
        try {
            MSmartThirdManager manager = MSmartSDK.getInstance().getThirdManager();
            manager.stopConfigureDevice();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}



